import json
from dvadmin.lowcode.models import OnlineApi,Datasource
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.decorators import action
from dvadmin.utils.json_response import SuccessResponse
from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse
from dvadmin.utils.sqlprocess import query_all_dict, list_to_dict, dict_int_change
from dvadmin.utils.common import get_parameter_dic

from dvadmin.lowcode.utils.online import OnlineProcess
import logging


class OnlineApiSerializer(CustomModelSerializer):
    """
    区块-序列化器
    """

    class Meta:
        model = OnlineApi
        fields = "__all__"
        read_only_fields = ["id"]


# class AssetsViewSet(CustomModelViewSet):
#     """
#     物料管理
#     list:查询
#     create:新增
#     update:修改
#     retrieve:单例
#     destroy:删除
#     """
#     queryset = OnlineApi.objects.all()
#     serializer_class = OnlineApiSerializer


class OnlineApiPerViewSet(CustomModelViewSet):
    """
    在线接口管理
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = OnlineApi.objects.all()
    serializer_class = OnlineApiSerializer

    @action(methods=['POST'], detail=False)
    def cmd(self, request):
        # sql解析 测试运行
        try:
            # 参数解析 转字典
            dictobj = dict(request.data)
            requestdata = list_to_dict(dictobj['parameter'], request.user.id)
            # 执行sql并转字典
            obj  = Datasource.objects.filter(id=dictobj['datasource']).first()
            dictobj.update({
                "datatype": obj.datatype,
                "user": obj.user,
                "password": obj.password,
                "key": obj.key
            })
            prodect = OnlineProcess(dictobj, requestdata, request.user.id,True)
            data = prodect.get()
            return DetailResponse(data=data, msg="获取成功")
        except Exception as e:
            logging.error(e)
            return ErrorResponse(data=[], code=2000, msg=str(e))





class OnlinePerViewSet(CustomModelViewSet):
    """
    在线接口管理
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    permission_classes = []
    extra_filter_backends = []
    queryset = OnlineApi.objects.all()
    @action(methods=['GET'], detail=False)
    def api(self, request, pk):
        # 生产接口运行
        obj = self.queryset.filter(url=pk).first()
        # 获取get and  post参数  字典
        data = get_parameter_dic(request)
        if obj and obj.status == 1:
            if obj.is_login == 1 and  not request.user.is_authenticated:
                return ErrorResponse(data=[], msg="请先登入")
            if request.method == "GET":
                dictobj = {
                    "methods": obj.methods,
                    "status": obj.status,
                    "sql": obj.sql,
                    "datatyped": obj.datatyped,
                    "data_source": obj.data_source,
                    "parameter": json.loads(obj.parameter),
                    "datasource": obj.datasource.id,
                    "datatype": obj.datasource.datatype,
                    "user": obj.datasource.user,
                    "password": obj.datasource.password,
                    "key": obj.datasource.key
                }
                #
                try:
                    prodect = OnlineProcess(dictobj, data,request.user.id)
                    data = prodect.get()
                    return DetailResponse(data=data, msg="获取成功")
                except Exception as e:

                    return ErrorResponse(data=[], msg=str(e))
            else:
                return ErrorResponse(data=[], msg="接口地址异常")
        else:
            return ErrorResponse(data=[], msg="请求不存在")